package com.yonyou.pmclouds.projectpart.processor;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.consts.EnableStatusConst;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.projectpart.entity.ProjectPartVO;
import com.yonyou.pmclouds.projectpart.mapper.ProjectpartMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 工程部位编码级联修改
 * 当修改了编码，需要级联更新下级子节点的编码
 */
@Component
public class ProjectpartUpdateChildrenCodeProcessor implements SingleProcessor<ProjectPartVO>{

    @Autowired
    private ProjectpartMapper projectpartMapper;

    @Override
    public void process(ProjectPartVO vo, ProjectPartVO orig) throws BusinessException {

        if(StringUtils.isEmpty(vo.getInnerCode())){
            //innercode用于查询所有子级（innerCode+innerCodeLength）
            throw new BusinessException("传参错误，innerCode为空");
        }
        ProjectPartVO dbVO = projectpartMapper.getById(vo.getPkProjectpart());
        String originalCode = null;
        if(dbVO != null){
            originalCode = dbVO.getScode();
            if(originalCode != null && !originalCode.equals(vo.getScode())){
                ProjectPartVO qryVO = new ProjectPartVO();
                qryVO.setPkProject(vo.getPkProject());
                qryVO.setInnerCode(vo.getInnerCode()+"%");
                qryVO.setInnerCodeLen(vo.getInnerCode().length());
                qryVO.setEnableStatus(EnableStatusConst.DISABLE);
                List<ProjectPartVO> result = projectpartMapper.queryVOsByCondition(qryVO);
                if(result.size() > 0){
                    //更新为新的code
                    String newCode = vo.getScode();
                    for(ProjectPartVO tmpVO : result){
                        tmpVO.setScode(tmpVO.getScode().replaceFirst(originalCode,newCode));
                        tmpVO.setModifier(RuntimeEnvironment.getLoginUserId());
                        tmpVO.setModifytime(new Date());
                        projectpartMapper.update(tmpVO);
                    }
                }
            }
        }
    }
}
